﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Telerik.WinControls.UI;
using Zvezda.FSO2.DB;
using Zvezda.FSO2.DB.DataSetFSOTableAdapters;
using System.Drawing;

namespace FSO
{
    public partial class FormInvoiceOut : Form, InterfaceObjDeleteableForm
    {
        //Тип счета
        RadListDataItem _productType = new RadListDataItem() { Text = "Товары/Работы", Value = true };
        RadListDataItem _serviceType = new RadListDataItem() { Text = "Услуги", Value = false };

        private DataSetFSO.INVOICE_OUTRow _rowInvOut;
		public bool AllowSave;

		DIRECTTableAdapter directTableAdapter1;
		VIEW_DIRECT_ITEMTableAdapter vieW_DIRECT_ITEMTableAdapter1;
		DataSetFSO.DIRECTRow _directRow;
        public FormInvoiceOut(int? pid)
        {
            InitializeComponent();

            _rowInvOut = dataSetFSO1.INVOICE_OUT.NewINVOICE_OUTRow();
            //Полю "Дата" по умолчанию присваиваем сегодняшнее число
            _rowInvOut.DATE = DateTime.Now.Date;

            if (pid == null)
            {
                //Этот счет по услугам
                _rowInvOut.TYPE = (bool) _serviceType.Value;

            }
            else
            {
                CONTRACTTableAdapter taContract = new CONTRACTTableAdapter();

                //Указываем, что этот счет не по услугам
                _rowInvOut.TYPE = (bool) _productType.Value;
                _rowInvOut.PID = pid.Value;

                //по умолчанию присваиваем организацию из договора
                int orgId = taContract.GetDataByPID(_rowInvOut.PID).First().NSI_ORGANIZATION_ID;
                if (orgId > 0)
                {
                    _rowInvOut.NSI_ORGANIZATION_ID = orgId;
                }
            }
            dataSetFSO1.INVOICE_OUT.AddINVOICE_OUTRow(_rowInvOut);

        }

        public FormInvoiceOut(DataSetFSO.INVOICE_OUTRow row)
        {
            InitializeComponent();

            invoicE_OUTTableAdapter1.FillByID(dataSetFSO1.INVOICE_OUT, row.ID);
            _rowInvOut = dataSetFSO1.INVOICE_OUT.FindByID(row.ID);
			
            this.Text = "Счет № " + _rowInvOut.NUMBER;
        }

        #region InterfaceObjectsMembers
        public int Delete()
        {
            _rowInvOut.Delete();

            invoicE_OUTTableAdapter1.Update(_rowInvOut);

            this.Close();

            return 0;
        }
		private void InitializeDirect(int? pid)
		{
			if (pid == null)
			{

			}
			else
			{
				CONTRACTTableAdapter taContract = new CONTRACTTableAdapter();
				directTableAdapter1 = new DIRECTTableAdapter();
				vieW_DIRECT_ITEMTableAdapter1 = new VIEW_DIRECT_ITEMTableAdapter();
				vieW_DIRECT_ITEMTableAdapter1.ClearBeforeFill = true;
				directTableAdapter1.ClearBeforeFill = true;

				_directRow = dataSetFSO1.DIRECT.NewDIRECTRow();
				if(!_rowInvOut.IsNUMBERNull())
					_directRow.NUMBER = "СЗ_СЧЕТ_" + _rowInvOut.NUMBER;
				_directRow.PID = pid.Value;
				//Полю "Дата" по умолчанию присваиваем сегодняшнее число
				_directRow.DATE = DateTime.Now.Date;
				dataSetFSO1.DIRECT.AddDIRECTRow(_directRow);
			}
		}

		private void DeleteDirect()
		{
			if (_directRow != null)
			{
				_directRow.Delete();
				directTableAdapter1.Update(_directRow);
			}
		}
        public int Save()
        {
            //Это значение вернется, если не сохраняться изменения
            int returnValue = -1;

            if (_rowInvOut.IsNUMBERNull())
            {
                MessageBox.Show(this, "Не заполнено обязательное поле \"Номер\".\nИзменения не будут сохранены", "Обязательное поле", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                //Сохраняем строку счета
                invoicE_OUTTableAdapter1.Update(_rowInvOut);

				if (_directRow != null)
				{
					if (_directRow.IsNUMBERNull())
						_directRow.NUMBER = "СЗ_СЧЕТ_" + _rowInvOut.NUMBER;
					//сохраняем служебную записку
					directTableAdapter1.Update(_directRow);
				}
				PRODUCT_UNITTableAdapter taPU = new PRODUCT_UNITTableAdapter();
                //Сохраняем платежи по счету
                foreach (DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow row in dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.Rows)
                {
                    DataSetFSO.PAY_IN_ON_INV_OUTRow payOnInv;
					
                    if (row.RowState == DataRowState.Added)
                    {
                        payOnInv = dataSetFSO1.PAY_IN_ON_INV_OUT.NewPAY_IN_ON_INV_OUTRow();

                        payOnInv.INVOICE_OUT_ID = _rowInvOut.ID;
                        payOnInv.PAYMENT_IN_ID = row.PAYMENT_IN_ID;
                        payOnInv.SUM_CUR = row.SUM_CUR;
                        payOnInv.SUM_RUB = row.SUM_RUB;
                        if (_rowInvOut.TYPE == (bool)_productType.Value)
                        {
                            payOnInv.PID = _rowInvOut.PID;
                        }

                        dataSetFSO1.PAY_IN_ON_INV_OUT.AddPAY_IN_ON_INV_OUTRow(payOnInv);
                        paY_IN_ON_INV_OUTTableAdapter1.Update(payOnInv);
                    }
                    else if (row.RowState == DataRowState.Modified)
                    {
                        payOnInv = paY_IN_ON_INV_OUTTableAdapter1.GetDataByID(row.ID).FindByID(row.ID);
                        payOnInv.SUM_CUR = row.SUM_CUR;
                        payOnInv.SUM_RUB = row.SUM_RUB;

                        paY_IN_ON_INV_OUTTableAdapter1.Update(payOnInv);
                    }
                    else if (row.RowState == DataRowState.Deleted)
                    {
                        int id = (int)row[dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.IDColumn, DataRowVersion.Original];

                        payOnInv = paY_IN_ON_INV_OUTTableAdapter1.GetDataByID(id).FindByID(id);
                        payOnInv.Delete();

                        paY_IN_ON_INV_OUTTableAdapter1.Update(payOnInv);
                    }
                }


                if (_rowInvOut.TYPE == (bool)_productType.Value)
                {
                    #region Сохранение товаров
                   
                    //Сохраняем оплачиваемые товары
                    foreach (DataSetFSO.VIEW_INV_OUT_ITEMRow row in dataSetFSO1.VIEW_INV_OUT_ITEM.Rows)
                    {
                        DataSetFSO.INVOICE_OUT_ITEMRow InvOutItemRow;
						DataSetFSO.PRODUCT_UNITRow productUnitRow;
                        if (row.RowState == DataRowState.Added)
                        {
                            InvOutItemRow = dataSetFSO1.INVOICE_OUT_ITEM.NewINVOICE_OUT_ITEMRow();
                            InvOutItemRow.INVOICE_OUT_ID = _rowInvOut.ID;
                            InvOutItemRow.PRODUCT_UNIT_ID = row.PRODUCT_UNIT_ID;
                            InvOutItemRow.PID = _rowInvOut.PID;
                            InvOutItemRow.SUM = row.SUM;
                            //InvOutItemRow.SUM_RUB = row.SUM_RUB;
                            dataSetFSO1.INVOICE_OUT_ITEM.AddINVOICE_OUT_ITEMRow(InvOutItemRow);

                            invoicE_OUT_ITEMTableAdapter1.Update(InvOutItemRow);

							//сохраняем данные для служебной записки
							if (_directRow != null)
							{
								productUnitRow = taPU.GetDataByID(row.PRODUCT_UNIT_ID).FindByID(row.PRODUCT_UNIT_ID);
								if (productUnitRow.IsDIRECT_NUMBERNull())
								{
									productUnitRow.DIRECT_NUMBER = _directRow.ID;
									taPU.Update(productUnitRow);
								}
							}
						}
                        else if (row.RowState == DataRowState.Modified)
                        {
                            InvOutItemRow = invoicE_OUT_ITEMTableAdapter1.GetDataByID(row.ID).FindByID(row.ID);
                            InvOutItemRow.SUM = row.SUM;
                            //InvOutItemRow.SUM_RUB = row.SUM_RUB;
							//сохраняем данные для служебной записки
							if (_directRow != null)
							{
								productUnitRow = taPU.GetDataByID(row.PRODUCT_UNIT_ID).FindByID(row.PRODUCT_UNIT_ID);
								if (productUnitRow.IsDIRECT_NUMBERNull())
								{
									productUnitRow.DIRECT_NUMBER = _directRow.ID;
									taPU.Update(productUnitRow);
								}
							}
                            invoicE_OUT_ITEMTableAdapter1.Update(InvOutItemRow);
                        }
                        else if (row.RowState == DataRowState.Deleted)
                        {
                            //Получаем данные удаленной строки из оригинальной версии (до удаления)
                            int rowId = (int)row[dataSetFSO1.VIEW_INV_OUT_ITEM.IDColumn, DataRowVersion.Original];
                            InvOutItemRow = invoicE_OUT_ITEMTableAdapter1.GetDataByID(rowId).FindByID(rowId);

							//сохраняем данные для служебной записки
							if (_directRow != null)
							{
								productUnitRow = taPU.GetDataByID(InvOutItemRow.PRODUCT_UNIT_ID).FindByID(InvOutItemRow.PRODUCT_UNIT_ID);
								//Переводим товар в статус "Заказан" только в случае если удаляем его из того же платежа,
								//в котором он был переведен в производство
								if (!productUnitRow.IsDIRECT_NUMBERNull() &&
									 productUnitRow.DIRECT_NUMBER == _directRow.ID)
								{
									productUnitRow.SetDIRECT_NUMBERNull();
									taPU.Update(productUnitRow);
								}
							}

                            InvOutItemRow.Delete();

                            invoicE_OUT_ITEMTableAdapter1.Update(InvOutItemRow);
                        }
                    }

                    #endregion
                }
                else if (_rowInvOut.TYPE == (bool)_serviceType.Value)
                {
                    #region Сохранение услуг
                    INVOICE_OUT_SERVICE_ITEMTableAdapter ta = new INVOICE_OUT_SERVICE_ITEMTableAdapter();

                    foreach (DataSetFSO.VIEW_INV_OUT_SERVICE_ITEMRow row in dataSetFSO1.VIEW_INV_OUT_SERVICE_ITEM.Rows)
                    {
                        DataSetFSO.INVOICE_OUT_SERVICE_ITEMRow invOutOnServRow;
                        if (row.RowState == DataRowState.Added)
                        {
                            invOutOnServRow = dataSetFSO1.INVOICE_OUT_SERVICE_ITEM.NewINVOICE_OUT_SERVICE_ITEMRow();
                            invOutOnServRow.INVOICE_OUT_ID = _rowInvOut.ID;
                            invOutOnServRow.NSI_SERVICE_ID = row.NSI_SERVICE_ID;
                            //payInOnServRow.PID = _payInRow.PID;
                            invOutOnServRow.COUNT = row.COUNT;

                            dataSetFSO1.INVOICE_OUT_SERVICE_ITEM.AddINVOICE_OUT_SERVICE_ITEMRow(invOutOnServRow);

                            ta.Update(invOutOnServRow);
                        }
                        else if (row.RowState == DataRowState.Modified)
                        {
                            invOutOnServRow = ta.GetDataByID(row.ID).FindByID(row.ID);
                            invOutOnServRow.COUNT = row.COUNT;

                            ta.Update(invOutOnServRow);
                        }
                        else if (row.RowState == DataRowState.Deleted)
                        {
                            //Получаем данные удаленной строки из оригинальной версии (до удаления)
                            int rowId = (int)row[dataSetFSO1.VIEW_INV_OUT_SERVICE_ITEM.IDColumn, DataRowVersion.Original];
                            invOutOnServRow = ta.GetDataByID(rowId).FindByID(rowId);
                            invOutOnServRow.Delete();

                            ta.Update(invOutOnServRow);
                        }
                    }
                    #endregion
                }
                RefreshForm();

                returnValue = 0;
            }

            return returnValue;
        }

        public int RefreshForm()
        {
            //Очищаем все таблицы
            foreach (DataTable table in dataSetFSO1.Tables)
            {
                if (!(table is DataSetFSO.INVOICE_OUTDataTable))
                {
                    table.Clear();
                }
            }

            //Заполняем постоянные для конкретного счета поля формы

            CONTRACTTableAdapter taContract = new CONTRACTTableAdapter();
            //COST_PROTOCOLTableAdapter taCostProtcol = new COST_PROTOCOLTableAdapter();
            NSI_ORGANIZATIONTableAdapter taOrg = new NSI_ORGANIZATIONTableAdapter();
            NSI_CURRENCYTableAdapter taCurrency = new NSI_CURRENCYTableAdapter();
            NSI_TYPE_OF_ACTIVITYTableAdapter taTypeOfAct = new NSI_TYPE_OF_ACTIVITYTableAdapter();
            //NSI_CURRENCYTableAdapter taCurrency = new NSI_CURRENCYTableAdapter();

            if (_rowInvOut.TYPE == (bool)_productType.Value)
            {
                #region Обновление счета за товары
                //Находим контракт, в рамках которого создан счет
                DataSetFSO.CONTRACTRow contract = taContract.GetDataByPID(_rowInvOut.PID).First();
                radLabelContract.Text = contract.NUMBER;
               
                //Организация
                if (!_rowInvOut.IsNSI_ORGANIZATION_IDNull())
                {
                    radLabelOrganization.Text = taOrg.GetDataById(_rowInvOut.NSI_ORGANIZATION_ID).FindByID(_rowInvOut.NSI_ORGANIZATION_ID).SHORT_NAME;
                }
                else
                {
                    radLabelOrganization.Text = "<Не указана>";
                }
               
                //Направление
                if (!contract.IsNSI_TYPE_OF_ACTIVITY_IDNull())
                {
                    radLabelTypeOfAct.Text = taTypeOfAct.GetData().FindByID(contract.NSI_TYPE_OF_ACTIVITY_ID).NAME;
                }
                else
                {
                    radLabelTypeOfAct.Text = "<Не указано>";
                }
                

                //Валюта

                radDropDownListCurrency.Items.Clear();
                foreach (DataSetFSO.NSI_CURRENCYRow row in taCurrency.GetData())
                {
                    RadListDataItem tmpItem = new RadListDataItem() { Text = row.SHORT_NAME, Value = row.ID };
                    radDropDownListCurrency.Items.Add(tmpItem);
                    //по умолчанию ставим счет рублевым
                    if (_rowInvOut.IsNSI_CURRENCY_IDNull() && tmpItem.Text == "RUB")
                    {
                        radDropDownListCurrency.SelectedItem = tmpItem;
                        _rowInvOut.NSI_CURRENCY_ID = (int)tmpItem.Value;
                    }
                }

                BindControls();

                //заполняем таблицу платежей по счету
                vieW_PAY_IN_ON_INV_OUTTableAdapter1.FillByInvOut(dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT, _rowInvOut.ID);
                //Заполняем товары счета
                vieW_INV_OUT_ITEMTableAdapter1.FillByInvOutID(dataSetFSO1.VIEW_INV_OUT_ITEM, _rowInvOut.ID);

                InitializePaymentsGrid();
                InitializeProductsGrid();


                InvoiceSummary();
                EvaluateRest();

                //Аванс и доплата
                radMaskedEditBoxPercent.Text = String.Format("{0:N2}%", _rowInvOut.ADVANCE_PERCENT);

                radMaskedEditBoxAddPayPercent.Text = String.Format("{0:N2}%", _rowInvOut.ADD_PAY_PERCENT);
                #endregion
            }
            else if(_rowInvOut.TYPE == (bool) _serviceType.Value)
            {
                #region Обновление счета за услуги

                //Организация
                if (!_rowInvOut.IsNSI_ORGANIZATION_IDNull())
                {
                    radLabelOrganization.Text = taOrg.GetDataById(_rowInvOut.NSI_ORGANIZATION_ID).FindByID(_rowInvOut.NSI_ORGANIZATION_ID).SHORT_NAME;
                }
                else
                {
                    radLabelOrganization.Text = "<Не указана>";
                }

                radDropDownListCurrency.Items.Clear();
                foreach (DataSetFSO.NSI_CURRENCYRow row in taCurrency.GetData())
                {
                    RadListDataItem tmpItem = new RadListDataItem() { Text = row.SHORT_NAME, Value = row.ID };
                    radDropDownListCurrency.Items.Add(tmpItem);
                    //по умолчанию ставим счет рублевым
                    if (_rowInvOut.IsNSI_CURRENCY_IDNull() && tmpItem.Text == "RUB")
                    {
                        radDropDownListCurrency.SelectedItem = tmpItem;
                        _rowInvOut.NSI_CURRENCY_ID = (int)tmpItem.Value;
                    }
                }

                BindControls();

                //заполняем таблицу платежей по счету
                vieW_PAY_IN_ON_INV_OUTTableAdapter1.FillByInvOut(dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT, _rowInvOut.ID);
                //Заполняем услуги
                vieW_INV_OUT_SERVICE_ITEMTableAdapter1.FillByInvOutID(dataSetFSO1.VIEW_INV_OUT_SERVICE_ITEM, _rowInvOut.ID);

                InitializePaymentsGrid();
                InitializeServiceGrid();

                EvaluateRest();

                #endregion
            }
            return 0;
        }

        public string FormName
        {
            get
            {
                string returnString = "Invoice_Out_";

                if (_rowInvOut.ID <= 0)
                {
                    returnString = returnString + DateTime.Now;
                }
                else
                {
                    returnString = returnString + _rowInvOut.ID;
                }

                return returnString;
            }
        }
        #endregion

        private void FormInvoiceOut_Load(object sender, EventArgs e)
        {
            if (_rowInvOut.TYPE == (bool)_productType.Value)
            {
                radButtonDeleteOrg.Visible = false;

                dataSetFSO1.VIEW_INV_OUT_ITEM.RowChanged += new DataRowChangeEventHandler(VIEW_INV_OUT_ITEM_RowChanged);

                dataSetFSO1.AGGR_PU_INV_OUT.RowChanged += new DataRowChangeEventHandler(AGGR_PU_INV_OUT_RowChanged);

                dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.ColumnChanged += new DataColumnChangeEventHandler(VIEW_PAY_IN_ON_INV_OUT_ColumnChanged);

                radGridViewItems.MultiSelect = true;
                radGridViewPayments.MultiSelect = true;
                radGridViewPayments.EnableGrouping = false;
            }
            else if(_rowInvOut.TYPE == (bool)_serviceType.Value)
            {
                radDropDownButtonAddFrom.Visible = false;
                radButtonAggrSum.Visible = false;
                radButtonNorma.Visible = false;
                radButtonEvaluateAdvace.Visible = false;
                panelRest.Visible = false;
                radMaskedEditBoxAddPayPercent.Enabled = false;
                radMaskedEditBoxPercent.Enabled = false;

                radGridViewItems.MultiSelect = true;
                radGridViewPayments.MultiSelect = true;
                radGridViewPayments.EnableGrouping = false;

                dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.ColumnChanged += new DataColumnChangeEventHandler(VIEW_PAY_IN_ON_INV_OUT_ColumnChanged);
            }

            RefreshForm();
        }

        #region Работа с таблицами датасета
        //изменение валютной колонки при изменении рублевой
        void VIEW_PAY_IN_ON_INV_OUT_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            if (e.Column == dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.SUM_CURColumn)
            {
                DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow curRow = (DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow)e.Row;
                decimal rate = FormHelper.GetRate(curRow.NSI_CURRENCY_NAME, curRow.PAYMENT_IN_DATE);

                curRow.SUM_RUB = curRow.SUM_CUR * rate;
            }
        }

        void AGGR_PU_INV_OUT_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Change)
            {
                //MessageBox.Show(e.Action.ToString());
                DataSetFSO.AGGR_PU_INV_OUTRow aggrInvRow = e.Row as DataSetFSO.AGGR_PU_INV_OUTRow;
                GridViewRowInfo rowInfo = (from rInf in radGridViewItems.MasterTemplate.Rows where ((int)rInf.Cells[dataSetFSO1.AGGR_PU_INV_OUT.NSI_PRODUCT_IDColumn.ColumnName].Value == aggrInvRow.NSI_PRODUCT_ID) select rInf).FirstOrDefault();
                if (rowInfo != null)
                {
                    if (aggrInvRow.COUNT < 1)
                    {
                        rowInfo.IsVisible = false;
                    }
                    else
                    {
                        rowInfo.IsVisible = true;
                    }
                }
            }
        }

        void VIEW_INV_OUT_ITEM_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Add)
            {
                //MessageBox.Show("Добавляемся!!!");
                DataSetFSO.VIEW_INV_OUT_ITEMRow rowInvInItem = e.Row as DataSetFSO.VIEW_INV_OUT_ITEMRow;

                DataSetFSO.AGGR_PU_INV_OUTRow aggrInvRow = (from aggrRow in dataSetFSO1.AGGR_PU_INV_OUT where (aggrRow.NSI_PRODUCT_ID == rowInvInItem.NSI_PRODUCT_ID) select aggrRow).FirstOrDefault();
                //Если такой записи нет а аггрегированной таблице
                if (aggrInvRow == null)
                {
                    aggrInvRow = dataSetFSO1.AGGR_PU_INV_OUT.NewAGGR_PU_INV_OUTRow();
                    aggrInvRow.INVOICE_OUT_ID = _rowInvOut.ID;
                    aggrInvRow.NSI_METER_NAME = rowInvInItem.NSI_METER_NAME;
                    aggrInvRow.NSI_PRODUCT_ID = rowInvInItem.NSI_PRODUCT_ID;
                    if (rowInvInItem.NSI_PRODUCT_ID == -1)
                    {
                        //значит данный товар - работа
                        aggrInvRow.PRODUCT_UNIT_NAME = "Работы";
                    }
                    else
                    {
                        aggrInvRow.PRODUCT_UNIT_NAME = rowInvInItem.PRODUCT_UNIT_NAME;
                    }
                    dataSetFSO1.AGGR_PU_INV_OUT.AddAGGR_PU_INV_OUTRow(aggrInvRow);
                }
                aggrInvRow.COUNT++;
            }
        }
        #endregion

        //Возвращает выбранную строку (вх платеж) с списке платежей
        public DataSetFSO.PAYMENT_INRow SelectedPaymentInRow
        {
            get
            {
                DataSetFSO.PAYMENT_INRow row;

                if (radGridViewPayments.SelectedRows.Count > 0)
                {
                    DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow tmp;
                    PAYMENT_INTableAdapter ta = new PAYMENT_INTableAdapter();

                    tmp = (DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow)(((DataRowView)(radGridViewPayments.SelectedRows.First()).DataBoundItem)).Row;
                    row = ta.GetDataByID(tmp.PAYMENT_IN_ID).FindByID(tmp.PAYMENT_IN_ID);
                }
                else
                {
                    row = null;
                }
                return row;
            }
        }

        private void BindControls()
        {
            //Номер счета
            radTextBoxNumber.DataBindings.Clear();
            radTextBoxNumber.DataBindings.Add("Text", _rowInvOut, dataSetFSO1.INVOICE_OUT.NUMBERColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Дата
            radDateTimePickerDate.DataBindings.Clear();
            radDateTimePickerDate.DataBindings.Add("Value", _rowInvOut, dataSetFSO1.INVOICE_OUT.DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Сумма и Валюта
            radMaskedEditBoxSum.DataBindings.Clear();
            radMaskedEditBoxSum.DataBindings.Add("Text", _rowInvOut, dataSetFSO1.INVOICE_OUT.SUMColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged, 0, "N2");

            radDropDownListCurrency.DataBindings.Clear();
            radDropDownListCurrency.DataBindings.Add("SelectedValue", _rowInvOut, dataSetFSO1.INVOICE_OUT.NSI_CURRENCY_IDColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            ////Аванс доплата

            ////Процент аванса
            //radMaskedEditBoxPercent.DataBindings.Clear();
            //radMaskedEditBoxPercent.DataBindings.Add("Text", _rowInvOut, dataSetFSO1.INVOICE_OUT.ADVANCE_PERCENTColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            
            ////Процент доплаты            
            //radMaskedEditBoxAddPayPercent.DataBindings.Clear();
            //radMaskedEditBoxAddPayPercent.DataBindings.Add("Text", _rowInvOut, dataSetFSO1.INVOICE_OUT.ADD_PAY_PERCENTColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Состояние
            radDropDownListState.DataBindings.Clear();
            radDropDownListState.DataBindings.Add("Text", _rowInvOut, dataSetFSO1.INVOICE_OUT.STATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Комментарии
            radTextBoxDescription.DataBindings.Clear();
            radTextBoxDescription.DataBindings.Add("Text", _rowInvOut, dataSetFSO1.INVOICE_OUT.DESCRIPTIONColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

        }

        private void InitializeServiceGrid()
        {
            GridViewTextBoxColumn colServName = new GridViewTextBoxColumn("SERVICE_NAME", dataSetFSO1.VIEW_INV_OUT_SERVICE_ITEM.NSI_SERVICE_NAMEColumn.ColumnName);
            colServName.HeaderText = "Наименование";
            colServName.ReadOnly = true;

            GridViewDecimalColumn colCount = new GridViewDecimalColumn("COUNT", dataSetFSO1.VIEW_INV_OUT_SERVICE_ITEM.COUNTColumn.ColumnName);
            colCount.HeaderText = "Кол.";
            colCount.FormatString = "{0:N2}";
            //colCount.DecimalPlaces = 0;
            colCount.Minimum = 0;

            GridViewTextBoxColumn colMeter = new GridViewTextBoxColumn("NSI_METER_NAME", dataSetFSO1.VIEW_INV_OUT_SERVICE_ITEM.NSI_METER_NAMEColumn.ColumnName);
            colMeter.HeaderText = "Ед.";
            colMeter.ReadOnly = true;

            radGridViewItems.MasterTemplate.Columns.Clear();
            radGridViewItems.MasterTemplate.Columns.Add(colServName);
            radGridViewItems.MasterTemplate.Columns.Add(colCount);
            radGridViewItems.MasterTemplate.Columns.Add(colMeter);

            radGridViewItems.AllowAddNewRow = false;
            radGridViewItems.AllowDeleteRow = false;
            radGridViewItems.AllowDragToGroup = false;
            radGridViewItems.ShowGroupPanel = false;
            radGridViewItems.EnableGrouping = false;

            radGridViewItems.DataSource = dataSetFSO1.VIEW_INV_OUT_SERVICE_ITEM;
        }

        private void InitializeProductsGrid()
        {

            //Колонки для агрегированной таблицы

            //Название товара
            GridViewTextBoxColumn colProdName = new GridViewTextBoxColumn("AGGR_PRODUCT_NAME", dataSetFSO1.AGGR_PU_INV_OUT.PRODUCT_UNIT_NAMEColumn.ColumnName);
            colProdName.HeaderText = "Имя";
            colProdName.ReadOnly = true;

            //Количество товара
            GridViewTextBoxColumn colCount = new GridViewTextBoxColumn("AGGR_COUNT", dataSetFSO1.AGGR_PU_INV_OUT.COUNTColumn.ColumnName);
            colCount.HeaderText = "Кол.";
            colCount.ReadOnly = true;

            //Единица измерения
            GridViewTextBoxColumn colAggrNSIMeter = new GridViewTextBoxColumn("AGGR_NSI_METER", dataSetFSO1.AGGR_PU_INV_OUT.NSI_METER_NAMEColumn.ColumnName);
            colAggrNSIMeter.HeaderText = "ед.";
            colAggrNSIMeter.ReadOnly = true;
            
            //Общая сумма товара данного наименования в валюте
            GridViewDecimalColumn colAggrSumCur = new GridViewDecimalColumn("AGGR_SUM_CUR", dataSetFSO1.AGGR_PU_INV_OUT.INV_SUMColumn.ColumnName);
            colAggrSumCur.HeaderText = "Сумма (Вал.)";
            colAggrSumCur.FormatString = "{0:N2} " + radDropDownListCurrency.SelectedText;
            colAggrSumCur.Minimum = 0;

            ////то же самое в рублях
            //GridViewDecimalColumn colAggrSumRub = new GridViewDecimalColumn("AGGR_SUM_RUB", dataSetFSO1.AGGR_PU_PAY_IN.PAY_SUM_RUBColumn.ColumnName);
            //colAggrSumRub.HeaderText = "Сумма (Руб.)";
            //colAggrSumRub.FormatString = "{0:N2}";
            //colAggrSumRub.Minimum = 0;

            //соединительная колонка
            GridViewTextBoxColumn colNSIProdId = new GridViewTextBoxColumn(dataSetFSO1.AGGR_PU_INV_OUT.NSI_PRODUCT_IDColumn.ColumnName);
            colNSIProdId.IsVisible = false;
            colNSIProdId.VisibleInColumnChooser = false;

            radGridViewItems.MasterTemplate.Columns.Clear();
            radGridViewItems.MasterTemplate.Columns.Add(colProdName);
            radGridViewItems.MasterTemplate.Columns.Add(colNSIProdId);
            radGridViewItems.MasterTemplate.Columns.Add(colCount);
            radGridViewItems.MasterTemplate.Columns.Add(colAggrNSIMeter);
            radGridViewItems.MasterTemplate.Columns.Add(colAggrSumCur);
            //radGridViewItems.MasterTemplate.Columns.Add(colAggrSumRub);

            radGridViewItems.AllowAddNewRow = false;
            radGridViewItems.MasterTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;

            radGridViewItems.MasterTemplate.DataSource = dataSetFSO1.AGGR_PU_INV_OUT;


            //Таблица для единиц товара
            GridViewTemplate PUTemplate = new GridViewTemplate();
            GridViewTextBoxColumn colPUName = new GridViewTextBoxColumn("PU_NAME", dataSetFSO1.VIEW_INV_OUT_ITEM.PRODUCT_UNIT_NAMEColumn.ColumnName);
            colPUName.HeaderText = "Наименование";
            colPUName.ReadOnly = true;

            //Состояние товара, по нему будем группировать
            GridViewTextBoxColumn colPUState = new GridViewTextBoxColumn("PU_STATE", dataSetFSO1.VIEW_INV_OUT_ITEM.NSI_PRODUCT_STATE_NAMEColumn.ColumnName);
            colPUState.HeaderText = "Состояние";
            colPUState.ReadOnly = true;

            //Цена товара
            GridViewDecimalColumn colPUCost = new GridViewDecimalColumn("PU_Cost", dataSetFSO1.VIEW_INV_OUT_ITEM.PRODUCT_UNIT_COSTColumn.ColumnName);
            colPUCost.HeaderText = "Цена";
            colPUCost.FormatString = "{0:N2}";
            colPUCost.ReadOnly = true;

            //Сумма оплаты за товар в валюте
            GridViewDecimalColumn colPUSumCur = new GridViewDecimalColumn("PU_SUM_CUR", dataSetFSO1.VIEW_INV_OUT_ITEM.SUMColumn.ColumnName);
            colPUSumCur.HeaderText = "Сумма";
            colPUSumCur.FormatString = "{0:N2}";
            //Валюта
            GridViewTextBoxColumn colPUCurName = new GridViewTextBoxColumn("PU_CURRENCY_NAME", dataSetFSO1.VIEW_INV_OUT_ITEM.NSI_CURRENCY_NAMEColumn.ColumnName);
            colPUCurName.HeaderText = "Вал.";
            colPUCurName.ReadOnly = true;

            // % оплаты
            GridViewDecimalColumn colPUPerPay = new GridViewDecimalColumn("PU_PER_PAY", dataSetFSO1.VIEW_INV_OUT_ITEM.PAY_PERColumn.ColumnName);
            colPUPerPay.HeaderText = "% оплаты";
            colPUPerPay.FormatString = "{0:N2}%";
            colPUPerPay.ReadOnly = true;

            //Сумма выставленных счетов на товар
            //GridViewDecimalColumn colPUInvOutSum = new GridViewDecimalColumn("PU_INV_IN_SUM", dataSetFSO1.VIEW_PAY_IN_ITEM.INVOICE_IN_SUMColumn.ColumnName);
            //colPUInvOutSum.HeaderText = "Выставлено счетов";
            //colPUInvOutSum.FormatString = "{0:N2}";

            ////№ и Название этапа Кп
            GridViewTextBoxColumn colPUCPStageName = new GridViewTextBoxColumn("PU_CP_STAGE_NUMBER", dataSetFSO1.VIEW_INV_OUT_ITEM.CP_STAGE_NUMBERColumn.ColumnName);
            colPUCPStageName.HeaderText = "КП\\№ Этап";

            //Конец этапа
            GridViewDateTimeColumn colPUCPEndDate = new GridViewDateTimeColumn("PU_CP_END_DATE", dataSetFSO1.VIEW_INV_OUT_ITEM.CP_STAGE_END_DATEColumn.ColumnName);
            colPUCPEndDate.HeaderText = "Отгрузка";
            colPUCPEndDate.FormatString = "{0:d}";
            colPUCPEndDate.ReadOnly = true;

            //№ счет-фактуры
            GridViewTextBoxColumn colVatInvNum = new GridViewTextBoxColumn("PU_VAT_INV_NUM", dataSetFSO1.VIEW_INV_OUT_ITEM.VAT_INVOICE_NUMBERColumn.ColumnName);
            colVatInvNum.HeaderText = "№ С-Ф";
            colVatInvNum.ReadOnly = true;

            //ID счет-фактуры
            GridViewTextBoxColumn colVatInvId = new GridViewTextBoxColumn("PU_VAT_ID", dataSetFSO1.VIEW_INV_OUT_ITEM.VAT_INVOICE_IDColumn.ColumnName);
            colVatInvId.IsVisible = false;

            //Дата счет-фактуры
            GridViewTextBoxColumn colVatInvDate = new GridViewTextBoxColumn("PU_VAT_INVOICE_DATE", dataSetFSO1.VIEW_INV_OUT_ITEM.VAT_INVOICE_DATEColumn.ColumnName);
            colVatInvDate.HeaderText = "Дата С-Ф";
            colVatInvDate.ReadOnly = true;
            //colVatInvDate.FormatString = "{0:d}";

            //№ счета
            //GridViewTextBoxColumn colInvOutNum = new GridViewTextBoxColumn("PU_INVOICE_OUT_NUMBER", dataSetFSO1.VIEW_INV_OUT_ITEM.INVOICE_OUT_NUMBERColumn.ColumnName);
            //colInvOutNum.HeaderText = "№ счета";
            //colInvOutNum.ReadOnly = true;

            ////Дата платежа
            //GridViewTextBoxColumn colPayInDate = new GridViewTextBoxColumn("PU_PAYMENT_IN_ITEM_DATE", dataSetFSO1.VIEW_INV_OUT_ITEM.PAYMENT_IN_ITEM_DATEColumn.ColumnName);
            //colPayInDate.HeaderText = "Дата платежа";
            //colPayInDate.ReadOnly = true;

			//номер чертежа
			GridViewTextBoxColumn colDrawing = new GridViewTextBoxColumn("PU_N_DRAWING", dataSetFSO1.VIEW_INV_OUT_ITEM.N_DRAWINGColumn.ColumnName);
			colDrawing.HeaderText = "№ чертежа";
			colDrawing.ReadOnly = true;


            //Статус изделия
            GridViewTextBoxColumn colProductState = new GridViewTextBoxColumn("PU_NSI_PRODUCT_STATE_NAME", dataSetFSO1.VIEW_INV_OUT_ITEM.NSI_PRODUCT_STATE_NAMEColumn.ColumnName);
            colProductState.HeaderText = "Статус изделия";
            colProductState.ReadOnly = true;

            //Группа товара
			GridViewTextBoxColumn colProductGroup = new GridViewTextBoxColumn("PU_PROD_GROUP", dataSetFSO1.VIEW_INV_OUT_ITEM.NSI_PROD_GROUP_NAMEColumn.ColumnName);
            colProductGroup.HeaderText = "Группа товара";
            colProductGroup.ReadOnly = true;

            //добавляем событие двойного клика для раскрытия информации по счет-фактуре
            radGridViewItems.CellDoubleClick += new GridViewCellEventHandler(radGridViewItems_CellDoubleClick);
            radGridViewItems.CellFormatting += new CellFormattingEventHandler(radGridViewItems_CellFormatting);
            //Соединительное поле
            GridViewTextBoxColumn colPUNSIProdId = new GridViewTextBoxColumn(dataSetFSO1.VIEW_INV_OUT_ITEM.NSI_PRODUCT_IDColumn.ColumnName);
            colPUNSIProdId.IsVisible = false;
            colPUNSIProdId.VisibleInColumnChooser = false;
            colPUNSIProdId.ReadOnly = true;

            PUTemplate.Columns.Clear();
            PUTemplate.Columns.Add(colPUName);
            PUTemplate.Columns.Add(colPUSumCur);
            PUTemplate.Columns.Add(colPUCurName);
            PUTemplate.Columns.Add(colPUCost);
            PUTemplate.Columns.Add(colPUPerPay);
            PUTemplate.Columns.Add(colPUCPStageName);
            PUTemplate.Columns.Add(colPUCPEndDate);
            PUTemplate.Columns.Add(colVatInvNum);
            PUTemplate.Columns.Add(colVatInvId);
            PUTemplate.Columns.Add(colVatInvDate);
            //PUTemplate.Columns.Add(colInvOutNum);
            //PUTemplate.Columns.Add(colPayInDate);
			PUTemplate.Columns.Add(colDrawing);
            PUTemplate.Columns.Add(colProductState);
            PUTemplate.Columns.Add(colProductGroup);
            PUTemplate.Columns.Add(colPUNSIProdId);
            PUTemplate.DataSource = dataSetFSO1.VIEW_INV_OUT_ITEM;
            PUTemplate.ShowFilteringRow = false;
            PUTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
            PUTemplate.AllowAddNewRow = false;
            PUTemplate.AllowDeleteRow = false;

            radGridViewItems.Templates.Clear();
            radGridViewItems.Templates.Add(PUTemplate);

            GridViewRelation relation = new GridViewRelation(radGridViewItems.MasterTemplate, PUTemplate);
            relation.ParentColumnNames.Add(dataSetFSO1.AGGR_PU_INV_OUT.NSI_PRODUCT_IDColumn.ColumnName);
            relation.ChildColumnNames.Add(dataSetFSO1.VIEW_INV_OUT_ITEM.NSI_PRODUCT_IDColumn.ColumnName);
            relation.RelationName = "CONTRACT_CONTRACT";

            radGridViewItems.Relations.Clear();
            radGridViewItems.Relations.Add(relation);

            radGridViewItems.Dock = DockStyle.Fill;
            radGridViewItems.ShowGroupPanel = false;
        }

        /// <summary>
        /// Функция создана для подчеркивания номера накладной, к которой привязан товар если он существует
        /// для того что бы номер накладной выглядел как ссылка на открытие формы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void radGridViewItems_CellFormatting(object sender, CellFormattingEventArgs e)
        {
            if (e.CellElement is GridDataCellElement)
            {
                if (((GridViewDataColumn)e.CellElement.ColumnInfo).FieldName == "VAT_INVOICE_NUMBER")
                {
                    var font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Underline);
                    e.CellElement.Font = font;
                }
            }  
        }

        /// <summary>
        /// Функция создана для обработки двойного клика по полю с номером накладной в гриде
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void radGridViewItems_CellDoubleClick(object sender, GridViewCellEventArgs e)
        {
            if (e.Column.FieldName == "VAT_INVOICE_NUMBER")
            {
                //получаем ячейку по которой кликнули
                var cell = ((GridDataCellElement)sender);
                //получаемт ID накладной из невидимой колонки которая следует сразу за колонкой с номером
                var vatId = cell.RowInfo.Cells[cell.ColumnIndex + 1].Value;
                //проверяем что не пусто
                if (vatId != DBNull.Value)
                {
                    //адаптер для получения данных о накладной из БД
                    VAT_INVOICETableAdapter taVat = new VAT_INVOICETableAdapter();
                    int id = int.Parse(vatId.ToString());
                    //открываем на просмотр выбранную накладную
                    FormVatInvoice vatForm = new FormVatInvoice(taVat.GetDataByID(id).First());
                    if (!FormHelper.HasOpenedForm(vatForm.FormName))
                    {
                        vatForm.MdiParent = FormHelper.MainForm;
                        vatForm.Show();
                        vatForm.Select();
                    }
                }
            }
        }

        private void InitializePaymentsGrid()
        {
            //Платежи
            GridViewTextBoxColumn colPayNum = new GridViewTextBoxColumn("PAYMENT_IN_NUMBER", dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.PAYMENT_IN_NUMBERColumn.ColumnName);
            colPayNum.HeaderText = "№";
            colPayNum.ReadOnly = true;
            GridViewDecimalColumn colSumRub = new GridViewDecimalColumn("SUM_RUB", dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.SUM_RUBColumn.ColumnName);
            colSumRub.HeaderText = "Сумма списания";
            colSumRub.Minimum = 0;
            colSumRub.FormatString = "{0:N2} руб.";
            colSumRub.ReadOnly = true;
            GridViewDecimalColumn colSumCur = new GridViewDecimalColumn("SUM_CUR", dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.SUM_CURColumn.ColumnName);
            colSumCur.HeaderText = "Сумма списания";
            colSumCur.Minimum = 0;
            colSumCur.FormatString = "{0:N2} " + radDropDownListCurrency.SelectedText;
            GridViewDateTimeColumn colPayDate = new GridViewDateTimeColumn("DATE", dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.PAYMENT_IN_DATEColumn.ColumnName);
            colPayDate.HeaderText = "Дата платежа";
            colPayDate.FormatString = "{0:d}";
            colPayDate.ReadOnly = true;


            radGridViewPayments.MasterTemplate.Columns.Clear();
            radGridViewPayments.MasterTemplate.Columns.Add(colPayNum);
            radGridViewPayments.MasterTemplate.Columns.Add(colSumRub);
            radGridViewPayments.MasterTemplate.Columns.Add(colSumCur);
            radGridViewPayments.MasterTemplate.Columns.Add(colPayDate);

            radGridViewPayments.AllowAddNewRow = false;
            radGridViewPayments.AllowDeleteRow = false;

            radGridViewPayments.DataSource = dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT;
        }

		private void radButtonProductsToManufactoring_Click(object sender, EventArgs e)
		{
			InitializeDirect(_rowInvOut.PID);
			foreach (var item in dataSetFSO1.VIEW_INV_OUT_ITEM)
			{
				if (_directRow != null && item.NSI_PRODUCT_STATE_ID == 1)
				{
					if(!_directRow.IsNUMBERNull())
						item.DIRECT_NUMBER = _directRow.NUMBER;
					item.NSI_PRODUCT_STATE_ID = 2;
					item.NSI_PRODUCT_STATE_NAME = "В производстве";
				}
			}
		}
        private void radButtonAddProducts_Click(object sender, EventArgs e)
        {
            if (_rowInvOut.TYPE == (bool)_productType.Value)
            {
                #region Добавление продукции
                DialogFormSelectObject selectPUDialog = new DialogFormSelectObject(ObjctTypeEnum.PRODUCT_UNIT_FOR_INVOICE_OUT, _rowInvOut.PID);
                //Заполняем только теми товарами цена на которые указана в валюте счета
                (selectPUDialog.Control as UserControlSearchPrUnitForInvoiceOut).FillGridByPidCurName(_rowInvOut.PID, radDropDownListCurrency.SelectedText);
                if (selectPUDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    AddPUFromSelectDialog(selectPUDialog);
                }
                #endregion
            }
            else if (_rowInvOut.TYPE == (bool)_serviceType.Value)
            {
                #region Добавление услуг
                DialogFormSelectObject selectServiceDialog = new DialogFormSelectObject(ObjctTypeEnum.NSI_SERVICE);
                if (selectServiceDialog.ShowDialog() == DialogResult.OK)
                {
                    //selectPUDialog.SelectedRows
                    foreach (GridViewRowInfo rowInf in selectServiceDialog.SelectedRows)
                    {
                        DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                        if (drv != null && drv.Row is DataSetFSO.VIEW_SEARCH_NSI_SERVICERow)
                        {
                            DataSetFSO.VIEW_SEARCH_NSI_SERVICERow serviceRow = drv.Row as DataSetFSO.VIEW_SEARCH_NSI_SERVICERow;

                            try
                            {
                                DataSetFSO.VIEW_INV_OUT_SERVICE_ITEMRow rowInvOutOnServ = dataSetFSO1.VIEW_INV_OUT_SERVICE_ITEM.NewVIEW_INV_OUT_SERVICE_ITEMRow();

                                rowInvOutOnServ.INVOICE_OUT_ID = _rowInvOut.ID;
                                rowInvOutOnServ.NSI_SERVICE_ID = serviceRow.ID;

                                rowInvOutOnServ.NSI_SERVICE_NAME = serviceRow.SHORT_NAME;
                                rowInvOutOnServ.COUNT = serviceRow.COUNT;
                                rowInvOutOnServ.NSI_METER_NAME = serviceRow.NSI_METER_NAME;


                                dataSetFSO1.VIEW_INV_OUT_SERVICE_ITEM.AddVIEW_INV_OUT_SERVICE_ITEMRow(rowInvOutOnServ);

                                ////Изменяем аггрегированную таблицу


                            }
                            catch (ConstraintException)
                            {
                                MessageBox.Show("Данная услуга уже добавлена к счету!");
                            }
                        }
                    }
                }
                #endregion
            }
        }

        //Добавление товаров из диалога выбора
        private void AddPUFromSelectDialog(DialogFormSelectObject selectPUDialog)
        {
            foreach (GridViewRowInfo rowInf in selectPUDialog.SelectedRows)
            {
                DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                if (drv != null && drv.Row is DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow)
                {
                    DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow productUnitRow = drv.Row as DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow;

                    try
                    {
                        DataSetFSO.VIEW_INV_OUT_ITEMRow rowInvOutItem = dataSetFSO1.VIEW_INV_OUT_ITEM.NewVIEW_INV_OUT_ITEMRow();

                        rowInvOutItem.INVOICE_OUT_ID = _rowInvOut.ID;
                        rowInvOutItem.PRODUCT_UNIT_ID = productUnitRow.ID;
                        rowInvOutItem.CP_STAGE_ID = productUnitRow.CP_STAGE_ID;
                        if (!productUnitRow.IsNSI_PRODUCT_IDNull())
                        {
                            rowInvOutItem.NSI_PRODUCT_ID = productUnitRow.NSI_PRODUCT_ID;
                        }
                        //значит это работа
                        else
                        {
                            rowInvOutItem.NSI_PRODUCT_ID = -1;
                            //В базе это значение null поэтому приравниваем к единице
                            //productUnitRow.NSI_PRODUCT_ID = -1;
                        }
                        
                        rowInvOutItem.PRODUCT_UNIT_NAME = productUnitRow.NAME;
                        rowInvOutItem.CP_STAGE_END_DATE = productUnitRow.CP_STAGE_END_DATE;
                        rowInvOutItem.CP_STAGE_NUMBER = productUnitRow.CP_STAGE_NUMBER;
                        rowInvOutItem.PRODUCT_UNIT_COST = productUnitRow.COST;
                        rowInvOutItem.NSI_CURRENCY_NAME = productUnitRow.NSI_CURRENCY_NAME;
                        rowInvOutItem.PAY_PER = productUnitRow.PAY_PER;
                        rowInvOutItem.NSI_METER_NAME = productUnitRow.NSI_METER_NAME;
                        rowInvOutItem.NSI_CURRENCY_NAME = productUnitRow.NSI_CURRENCY_NAME;
                        rowInvOutItem.PRODUCT_UNIT_COST = productUnitRow.COST;
                        rowInvOutItem.NSI_PRODUCT_STATE_ID = productUnitRow.NSI_PRODUCT_STATE_ID;
                        //rowInvOutItem.INVOICE_OUT_NUMBER = productUnitRow.INVOICE_OUT_NUMBER;
                        //rowInvOutItem.INVOICE_OUT_DATE = productUnitRow.INVOICE_OUT_DATE;
                        if (!productUnitRow.IsVAT_INVOICE_IDNull())
                            rowInvOutItem.VAT_INVOICE_ID = productUnitRow.VAT_INVOICE_ID;
                        rowInvOutItem.VAT_INVOICE_DATE = productUnitRow.VAT_INVOICE_DATE1;
                        rowInvOutItem.VAT_INVOICE_NUMBER = productUnitRow.VAT_INVOICE_NUMBER;
                        rowInvOutItem.NSI_PRODUCT_STATE_NAME = productUnitRow.NSI_PRODUCT_STATE_NAME;
						try
						{
							rowInvOutItem.NSI_PROD_GROUP_NAME = productUnitRow.NSI_PROD_GROUP_NAME;
							rowInvOutItem.N_DRAWING = productUnitRow.N_DRAWING;
						}
						catch { } //работы или группа товара не указана
                        dataSetFSO1.VIEW_INV_OUT_ITEM.AddVIEW_INV_OUT_ITEMRow(rowInvOutItem);

                        ////Изменяем аггрегированную таблицу


                    }
                    catch (ConstraintException)
                    {
                        MessageBox.Show("Данный товар уже добавлен к платежу!");
                    }
                }
            }
        }

        private void radDropDownListCurrency_SelectedIndexChanging(object sender, Telerik.WinControls.UI.Data.PositionChangingCancelEventArgs e)
        {
            string curName = "---";
            foreach (DataSetFSO.VIEW_INV_OUT_ITEMRow row in dataSetFSO1.VIEW_INV_OUT_ITEM.Rows)
            { 
                //Инициализируем значение валюты
                if(curName == "---")
                {
                    curName = row.NSI_CURRENCY_NAME;
                }

                if (row.NSI_CURRENCY_NAME != curName)
                {
                    MessageBox.Show("В одном счете не может находиться продукция с цены которую указаны в различных валютах! Удалите данный счет и создайте заново, либо проверьте протоколы согласования цены!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel=true;
                }
            }
            //Если значение валюты всех товаров совпадают с валютой счета, то сменить валюту счета нельзя
            if (radDropDownListCurrency.SelectedText == curName)
            {
                e.Cancel = true;
            }
            //Если не совпадает, то сменить можно только на ту валюту в которой указаны цены продуктов(валюта должна быть одинаковой)
            else
            { 
                NSI_EXCHANGE_RATETableAdapter ta = new NSI_EXCHANGE_RATETableAdapter();
                int curId = (int) ta.getCurID(curName);
                foreach(RadListDataItem item in radDropDownListCurrency.Items)
                {
                    if ((int)item.Value == curId)
                    {
                        radDropDownListCurrency.SelectedItem = item;
                        break;
                    }
                }
            }
        }

        //Дабавление платежа
        private void radButtonAddPay_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject selectPayInDialog; 
            if (_rowInvOut.TYPE == (bool) _productType.Value)
            {

                selectPayInDialog = new DialogFormSelectObject(ObjctTypeEnum.PAYMENT_IN, _rowInvOut.PID);

            }
            else
            {
                //Если счет за услугам
                selectPayInDialog = new DialogFormSelectObject(ObjctTypeEnum.PAYMENT_IN);

                (selectPayInDialog.Control as UserControlSearchPaymentIn).FillPayOnService();
            }
            if (selectPayInDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                foreach (GridViewRowInfo rowInf in selectPayInDialog.SelectedRows)
                {
                    DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                    if (drv != null && drv.Row is DataSetFSO.VIEW_SEARCH_PAYMENT_INRow)
                    {
                        DataSetFSO.VIEW_SEARCH_PAYMENT_INRow payInRow = drv.Row as DataSetFSO.VIEW_SEARCH_PAYMENT_INRow;

                        try
                        {
                            DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow payOnInv = dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.NewVIEW_PAY_IN_ON_INV_OUTRow();

                            payOnInv.INVOICE_OUT_ID = _rowInvOut.ID;
                            payOnInv.PAYMENT_IN_ID = payInRow.ID;
                            payOnInv.PAYMENT_IN_NUMBER = payInRow.NUMBER;
                            if (_rowInvOut.TYPE == (bool)_productType.Value)
                            {
                                payOnInv.PID = _rowInvOut.PID;
                            }
                            payOnInv.NSI_CURRENCY_NAME = radDropDownListCurrency.SelectedText;
                            payOnInv.PAYMENT_IN_DATE = payInRow.DATE;

                            dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.AddVIEW_PAY_IN_ON_INV_OUTRow(payOnInv);

                        }
                        catch (ConstraintException)
                        {
                            MessageBox.Show("Этот счет уже добавлен к платежу!");
                        }

                    }
                }

            }
        }

        private void FormInvoiceOut_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (!AllowSave)
				return;
            if (_rowInvOut.RowState != DataRowState.Deleted && _rowInvOut.RowState != DataRowState.Detached && (_rowInvOut.RowState == DataRowState.Added || _rowInvOut.RowState == DataRowState.Modified || (dataSetFSO1.VIEW_INV_OUT_ITEM.GetChanges()) != null || (dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.GetChanges()) != null || dataSetFSO1.VIEW_INV_OUT_SERVICE_ITEM.GetChanges() != null))
            {
                DialogResult result = MessageBox.Show(this, "Были внесены изменения. Сохранить?", "Сохранить изменения?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    int SaveResult = this.Save();

                    if (SaveResult == -1)
                    {
                        e.Cancel = true;
                    }
                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
                else if (result == DialogResult.No)
                {
                    dataSetFSO1.RejectChanges();
                }
            }
        }

        //Открывает договор
        private void radLabelContract_DoubleClick(object sender, EventArgs e)
        {
            if (!_rowInvOut.IsPIDNull())
            {
                CONTRACTTableAdapter ta = new CONTRACTTableAdapter();
                FormContract contractForm = new FormContract(ta.GetDataByPID(_rowInvOut.PID).First());
                if (!FormHelper.HasOpenedForm(contractForm.FormName))
                {
                    contractForm.MdiParent = FormHelper.MainForm;
                    contractForm.Show();
                    contractForm.Select();
                }
            }
        }

        //Открывает организацию
        private void radLabelOrganization_DoubleClick(object sender, EventArgs e)
        {
            if (_rowInvOut.IsNSI_ORGANIZATION_IDNull())
            {
                DialogFormSelectObject dialog = new DialogFormSelectObject(ObjctTypeEnum.ORGANIZATION);
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    DataSetFSO.NSI_ORGANIZATIONRow org = (DataSetFSO.NSI_ORGANIZATIONRow)dialog.SelectedRow;
                    _rowInvOut.NSI_ORGANIZATION_ID = org.ID;
                    radLabelOrganization.Text = org.SHORT_NAME;
                }
            }
            else
            {
                NSI_ORGANIZATIONTableAdapter taOrg = new NSI_ORGANIZATIONTableAdapter();
                FormNSIOrganization orgForm = new FormNSIOrganization(taOrg.GetDataById(_rowInvOut.NSI_ORGANIZATION_ID).FindByID(_rowInvOut.NSI_ORGANIZATION_ID));
                if (!FormHelper.HasOpenedForm(orgForm.FormName))
                {
                    orgForm.MdiParent = FormHelper.MainForm;
                    orgForm.Show();
                    orgForm.Select();
                }
            }

        }

        //Удаление продукции
        private void radButtonDeleteProducts_Click(object sender, EventArgs e)
        {
            if (_rowInvOut.TYPE == (bool)_productType.Value)
            {
                DataSetFSO.VIEW_INV_OUT_ITEMRow tmpPURow;
                foreach (GridViewRowInfo rowInf in radGridViewItems.SelectedRows.ToList())
                {
                    if ((tmpPURow = (rowInf.DataBoundItem as DataRowView).Row as DataSetFSO.VIEW_INV_OUT_ITEMRow) != null)
                    {

                        //Получаем данные из оригинальной версии строки
                        int nsiProdId = tmpPURow.NSI_PRODUCT_ID;
                        //Изменяем данные агрегированной строки
                        DataSetFSO.AGGR_PU_INV_OUTRow aggrInvOutRow = (from aggrRow in dataSetFSO1.AGGR_PU_INV_OUT where (aggrRow.NSI_PRODUCT_ID == nsiProdId) select aggrRow).First();
                        aggrInvOutRow.COUNT--;
                        rowInf.Delete();
                    }
                }
            }
            else if (_rowInvOut.TYPE == (bool)_serviceType.Value)
            {
                foreach (GridViewRowInfo rowInf in radGridViewItems.SelectedRows.ToList())
                {
                    rowInf.Delete();
                }
            }
        }

        //Удаление связи с платежом
        private void radButtonDelPay_Click(object sender, EventArgs e)
        {
            foreach (GridViewRowInfo ri in radGridViewPayments.SelectedRows.ToList())
            {
                if (ri != null)
                {
                    ri.Delete();
                }
            }
        }

        //Открывает выбранный платеж
        private void radGridViewPayments_CellDoubleClick(object sender, GridViewCellEventArgs e)
        {
            DataSetFSO.PAYMENT_INRow payInRow = this.SelectedPaymentInRow;
            if (payInRow != null)
            {

                FormPaymentIn formPayIn = new FormPaymentIn(payInRow);
                if (!FormHelper.HasOpenedForm(formPayIn.FormName))
                {
                    formPayIn.MdiParent = FormHelper.MainForm;
                    formPayIn.Show();
                    formPayIn.Select();
                }

            }
        }

        private void radButtonNorma_Click(object sender, EventArgs e)
        {
            DataSetFSO.AGGR_PU_INV_OUTRow tmpAggrPURow;

            foreach (GridViewRowInfo rowInf in radGridViewItems.SelectedRows.ToList())
            {
                if ((tmpAggrPURow = (rowInf.DataBoundItem as DataRowView).Row as DataSetFSO.AGGR_PU_INV_OUTRow) != null)
                {
                    //Проходим по всем товарам с тем же NSI_PRODUCT_ID и устанавливаем среднюю цену
                    List<DataSetFSO.VIEW_INV_OUT_ITEMRow> invItems = (from row in dataSetFSO1.VIEW_INV_OUT_ITEM where row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached && row.NSI_PRODUCT_ID == tmpAggrPURow.NSI_PRODUCT_ID select row).ToList();
                    int itemCount = invItems.Count;
                    //tmpAggrPURow.INV_SUM = 0;
                    for (int i = 0; i < itemCount; i++)
                    {
                        //Приравниваем к среднему значению
                        invItems[i].SUM = tmpAggrPURow.INV_SUM / itemCount;
                        
                    }
                }
            }
        }

        private void radButtonAggrSum_Click(object sender, EventArgs e)
        {
            InvoiceSummary();
        }

        //Пересчет агрегированных сумм
        private void InvoiceSummary()
        {
            foreach (DataSetFSO.AGGR_PU_INV_OUTRow tmpAggrPURow in dataSetFSO1.AGGR_PU_INV_OUT.Rows)
            {
                //Проходим по всем товарам с тем же NSI_PRODUCT_ID и устанавливаем складываем цену;
                List<DataSetFSO.VIEW_INV_OUT_ITEMRow> payItems = (from row in dataSetFSO1.VIEW_INV_OUT_ITEM where row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached && row.NSI_PRODUCT_ID == tmpAggrPURow.NSI_PRODUCT_ID select row).ToList();
                int itemCount = payItems.Count;

                tmpAggrPURow.INV_SUM = 0;
                //tmpAggrPURow.PAY_SUM_CUR = 0;
                for (int i = 0; i < itemCount; i++)
                {
                    tmpAggrPURow.INV_SUM += payItems[i].SUM;
                }
            }
        }

        private void radButtonEvaluateRest_Click(object sender, EventArgs e)
        {
            EvaluateRest();
        }

        //Вычисление остатков
        private void EvaluateRest()
        {
            decimal productRest = _rowInvOut.SUM - (from row in dataSetFSO1.VIEW_INV_OUT_ITEM where row.RowState!= DataRowState.Deleted && row.RowState != DataRowState.Detached select row.SUM).Sum();
            decimal payRest = _rowInvOut.SUM - (from row in dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT where row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached select row.SUM_CUR).Sum();

            string curName = radDropDownListCurrency.SelectedText;
            decimal rate = FormHelper.GetRate(curName, DateTime.Now.Date);

            radLabelPayRestCur.Text = String.Format("{0:N2} {1}", payRest, curName);
            radLabelProductRestCur.Text = String.Format("{0:N2} {1}.", productRest, curName);

            radLabelPayRestRub.Text = String.Format("{0:N2} Руб.", payRest*rate);
            radLabelProductRestRub.Text = String.Format("{0:N2} Руб.", productRest * rate);

        }

        private void radButtonEvaluateAdvace_Click(object sender, EventArgs e)
        {
            EvaluateAdvance();
        }

        //Вычисление % аванса и доплаты
        private void EvaluateAdvance()
        {
            decimal advance = 0;
            decimal payAdd = 0;
            int advanceIter = 0;
            int payAddIter = 0;
            foreach (DataSetFSO.VIEW_INV_OUT_ITEMRow row in dataSetFSO1.VIEW_INV_OUT_ITEM.Rows)
            {
                if (row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached)
                {
                    decimal sum=0;
                    //try
                    //{
                    //    //Узнаем сумму счетов на этот товар до даты текущего счета
                    //    sum = (decimal)vieW_INV_OUT_ITEMTableAdapter1.getInvSumByDate(row.PRODUCT_UNIT_ID, _rowInvOut.DATE);
                    //}
                    //catch (InvalidOperationException)
                    //{
                    //    //Значит не было счетов
                    //    sum = 0;
                    //}

                    sum += row.SUM;

                    switch (row.NSI_PRODUCT_STATE_ID)
                    {
                        case 1:
                        case 2:
                            advanceIter++;
                            advance += sum / row.PRODUCT_UNIT_COST;
                            //advance = ((advanceIter - 1) * advance + (sum / row.PRODUCT_UNIT_COST)) / advanceIter;
                            break;
                        case 3:
                        case 4:
                            payAddIter++;
                            payAdd += sum / row.PRODUCT_UNIT_COST;
                            //payAdd = ((payAddIter - 1) * payAdd + (sum / row.PRODUCT_UNIT_COST)) / payAddIter;
                            break;
                        default:
                            break;

                    }
                    //MessageBox.Show(sum.ToString());
                }
            }
            if (advanceIter != 0)
                advance = 100 * advance / advanceIter;
            if (payAddIter != 0)
                payAdd = 100 * payAdd / payAddIter;
            radMaskedEditBoxPercent.Text = String.Format("{0:N2}%", advance);
            _rowInvOut.ADVANCE_PERCENT = advance;

            radMaskedEditBoxAddPayPercent.Text = String.Format("{0:N2}%", payAdd);
            _rowInvOut.ADD_PAY_PERCENT = payAdd;
        }

        private void radMenuItemAddFromPayIn_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject selectPayInDialog = new DialogFormSelectObject(ObjctTypeEnum.PAYMENT_IN, _rowInvOut.PID);
            DataSetFSO.PAYMENT_INRow payIn;
            if (selectPayInDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && (payIn = selectPayInDialog.SelectedRow as DataSetFSO.PAYMENT_INRow) != null)
            {
                DialogFormSelectObject selectPUDialog = new DialogFormSelectObject(ObjctTypeEnum.PRUDUCT_UNIT_FOR_FORMS, _rowInvOut.PID);
                (selectPUDialog.Control as UserControlSearchPrUnitByID).FillGridByPayInID(payIn.ID, radDropDownListCurrency.SelectedText);

                if (selectPUDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    AddPUFromSelectDialog(selectPUDialog);
                }

            }
        }

		void radMenuItemFromInvOut_Click(object sender, System.EventArgs e)
		{
			DialogFormSelectObject selectVatInvtDialog = new DialogFormSelectObject(ObjctTypeEnum.INVOICE_OUT, _rowInvOut.PID);
			DataSetFSO.INVOICE_OUTRow vatInv;
			if (selectVatInvtDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && (vatInv = selectVatInvtDialog.SelectedRow as DataSetFSO.INVOICE_OUTRow) != null)
			{
				DialogFormSelectObject selectPUDialog = new DialogFormSelectObject(ObjctTypeEnum.PRUDUCT_UNIT_FOR_FORMS, _rowInvOut.PID);
				(selectPUDialog.Control as UserControlSearchPrUnitByID).FillGridByVatInvoiceID(vatInv.ID, radDropDownListCurrency.SelectedText);

				if (selectPUDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
				{
					AddPUFromSelectDialog(selectPUDialog);
				}

			}
		}
        private void radMenuItemFromVatInv_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject selectVatInvtDialog = new DialogFormSelectObject(ObjctTypeEnum.VAT_INVOICE, _rowInvOut.PID);
            DataSetFSO.VAT_INVOICERow vatInv;
            if (selectVatInvtDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && (vatInv = selectVatInvtDialog.SelectedRow as DataSetFSO.VAT_INVOICERow) != null)
            {
                DialogFormSelectObject selectPUDialog = new DialogFormSelectObject(ObjctTypeEnum.PRUDUCT_UNIT_FOR_FORMS, _rowInvOut.PID);
                (selectPUDialog.Control as UserControlSearchPrUnitByID).FillGridByVatInvoiceID(vatInv.ID, radDropDownListCurrency.SelectedText);

                if (selectPUDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    AddPUFromSelectDialog(selectPUDialog);
                }

            }
        }

        private void radButtonDeleteOrg_Click(object sender, EventArgs e)
        {
            _rowInvOut.SetNSI_ORGANIZATION_IDNull();
            radLabelOrganization.Text = "<Не указана>";
        }
       
    }
}
